package com.neuedu.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.neuedu.entity.User;
import com.neuedu.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author: MARK
 * @Date: 2019/7/29 19:14
 * @version: 1.0.0
 * @Description:
 */

@RestController
@Slf4j
@ResponseBody
@RequestMapping(value = "/user" ,produces = "application/json; charset=utf-8")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/user")
    public String users(){

        log.info("-------用户列表controller进来了");
        List<User> list = userService.getAll();
        String json = JSON.toJSONString(list);
        return json;
    }

    @PostMapping("/add")
    /**
     * @param [user] 实体类实现参数绑定
     * @return void
     * @create: 9:51 2019/8/1
     * @author MARK
     * @Description:
     */
    public void add(@Valid User user, BindingResult result){
        if (result.hasErrors()) {
            // 输出错误信息
            List<ObjectError> allErrors = result.getAllErrors();
            for (ObjectError objectError : allErrors) {
                // 输出错误信息
                log.info("-------"+objectError.getDefaultMessage());
            }
        }
        log.info("-------add  controller");
        log.info("-------username: " + user.getUsername());
        log.info("-------birth: " + user.getBirth());
        log.info("-------" + user.getPassword());
        userService.add(user);
    }

    /**
     * @param
     * @return void
     * @create: 9:51 2019/8/1
     * @author MARK
     * @Description: 实体类实现参数绑定
     */
    @PostMapping("/update")
    public void update(User user){
        log.info("-------update  controller");
        log.info("-------"+user.getBirth());
        userService.update(user);
    }

    @PostMapping("/delete")
    public void delete(HttpServletRequest request){
        log.info("-------delete controller");
        Integer id = Integer.parseInt(request.getParameter("id"));
        userService.delete(id);
    }

    @PostMapping("/json")
    public User getJson(@RequestBody User user){
        log.info("-------"+user);
        return user;
    }
}
